package com.xupt.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xupt.utils.HttpUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Random;

@Controller
public class OpenController {
    /**
     * 获取七天图片接口地址
     */
    static  final String API_URL = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=7&mkt=zh-CN";

    /**
     * 默认图片地址
     */
    static final String DEFAULT_IMG = "https://cn.bing.com//th?id=OHR.RedRoofTile_ZH-CN0528575898_1920x1080.jpg";

    @GetMapping("/")
    public Object getImage() {
        String data = HttpUtil.doGet(API_URL);
        JSONObject jsonObject = JSONObject.parseObject(data);
        try {
            JSONArray jsonArray = jsonObject.getJSONArray("images");
            if (!jsonArray.isEmpty()) {
                //获取随机一个
                Random random = new Random();
                int randKey = random.nextInt(jsonArray.size());
                JSONObject itemObject = (JSONObject) jsonArray.get(randKey);
                //获取链接
                return "redirect:https://cn.bing.com/" + itemObject.getString("url");
            } else {
                return "redirect:" + DEFAULT_IMG;
            }
        } catch (Exception e) {
            return "redirect:" + DEFAULT_IMG;
        }
    }
}
